package org.bonorsoft.modules.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class QrCode {

    @Value(value = "${william.path.upload}")
    private String uploadpath;

	//绘制二维码图片
	public String setQRCodeImg(String id, String code) throws Exception {
		//String content = "http://47.105.96.130:8080/HomeSystem/mobilePhone/index.html?id="+id+"&user="+addPeople;
        String content = "http://47.105.96.130:80/view/viewinfo.html?id="+id;
        String logoParentPath = uploadpath + "/qrcode/";
        File file = new File(logoParentPath );
        if (!file.exists()) {
            file.mkdirs();// 创建文件根目录
        }
        String format = "png";
        int width = 500;
        int height = 600;
        BufferedImage image = genBarcode(content, width, height);
        // 可通过输出流输出到页面,也可直接保存到文件
        OutputStream outStream = null;
        String qrpath = new Date().getTime() + ".png";
        String path = logoParentPath + qrpath;
        try {
            outStream = new FileOutputStream(new File(path));   
            //BufferedImage image = toBufferedImage(bitMatrix);
            ImageIO.write(image, format, outStream);
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 添加文字效果
        int fontSize = 30; // 字体大小
        int fontStyle = 0; // 字体风格
        String text = code;
        String newPath = new Date().getTime() + ".png";
        String withTextPath = logoParentPath + newPath;
        pressText(text, withTextPath, path, fontStyle, Color.BLACK, fontSize, width, height);
//	        System.out.println("withTextPath====="+withTextPath);
        //System.out.println(pressText(text, withTextPath, path, fontStyle, Color.BLACK, fontSize, width, height));
//        if(pressText(text, withTextPath, path, fontStyle, Color.BLACK, fontSize, width, height)) {
//        	if(ImageSynthesis(outPath,withTextPath)) {
//        		return true;
//        	}
//        }
        return "qrcode/" + newPath;
     }
	/**
     * 得到BufferedImage
     *  彩色二维码
     * @param content 二维码显示的文本
     * @param width   二维码的宽度
     * @param height  二维码的高度
     * @return
     * @throws WriterException
     * @throws IOException
     */
    private BufferedImage genBarcode(String content, int width, int height) throws WriterException, IOException {
        //定义二维码内容参数
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        //设置字符集编码格式
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //设置容错等级，在这里我们使用M级别
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        int margin = 0;
        hints.put(EncodeHintType.MARGIN, margin); // 指定二维码四周白色区域大小
        // 生成二维码，参数顺序分别为：编码内容，编码类型，生成图片宽度，生成图片高度，设置参数
        BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
 
        // 二维矩阵转为一维像素数组
        int[] pixels = new int[width * height];
 
        for (int y = 0; y < matrix.getHeight(); y++) {
            for (int x = 0; x < matrix.getWidth(); x++) {
                // 二维码颜色（RGB）
                int num1 = (int) (50 - (50.0 - 13.0) / matrix.getHeight() * (y + 1));
                int num2 = (int) (165 - (165.0 - 72.0) / matrix.getHeight() * (y + 1));
                int num3 = (int) (162 - (162.0 - 107.0) / matrix.getHeight() * (y + 1));
                Color color = new Color(num1, num2, num3);
                int colorInt = color.getRGB();
                // 此处可以修改二维码的颜色，可以分别制定二维码和背景的颜色；
                pixels[y * width + x] = matrix.get(x, y) ? 0x000000:0xffffff;// 0x000000:0xffffff
            }
        }
 
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        image.getRaster().setDataElements(0, 0, width, height, pixels);
 
        return image;
    }
    
    /**
     * 为图片添加文字
     * @param pressText 文字
     * @param newImage 带文字的图片
     * @param targetImage 需要添加文字的图片
     * @param fontStyle 字体风格
     * @param color 字体颜色
     * @param fontSize 字体大小
     * @param width 图片宽度
     * @param height 图片高度
     */
    public boolean pressText(String pressText, String newImage, String targetImage, int fontStyle, Color color, int fontSize, int width, int height) {
        // 计算文字开始的位置
        // x开始的位置：（图片宽度-字体大小*字的个数）/2
       int startX = (width-(fontSize*pressText.length()))/2 + fontSize;
       // y开始的位置：图片高度-（图片高度-图片宽度）/2
       int startY = height-(height-width)/2 + fontSize;
       try {
           File file = new File(targetImage);
           BufferedImage src = ImageIO.read(file);
           int imageW = src.getWidth(null);
           int imageH = src.getHeight(null);
           BufferedImage image = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_RGB);
           Graphics g = image.createGraphics();
           g.drawImage(src, 0, 0, imageW, imageH, null);
           g.setColor(color);
           g.setFont(new Font(null, fontStyle, fontSize));
           g.drawString(pressText, startX, startY);
           g.dispose();
           FileOutputStream out = new FileOutputStream(newImage);
           ImageIO.write(image, "png", out);
           out.close();
       } catch (Exception e) {
           e.printStackTrace();
           return false; 
       }
       return true; 
   }
    
    /*public static boolean ImageSynthesis(String outPath, String withTextPath) throws Exception {
		ImageIcon imgIcon=new ImageIcon(outPath);
		ImageIcon imgIconSmall=new ImageIcon(withTextPath); 
//		System.out.println("hecheng"+outPath);
		Image theImg =imgIcon.getImage(); 
		Image theImgSmall =imgIconSmall.getImage(); 
		
		int width=theImg.getWidth(null)==-1?200:theImg.getWidth(null); 
		int height= theImg.getHeight(null)==-1?200:theImg.getHeight(null); 
//		System.out.println(width);
//		System.out.println(height);
//		System.out.println(theImg);
		BufferedImage bimage = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB); 
		Graphics2D g=bimage.createGraphics(); 
		g.drawImage(theImg, 0, 0, null ); 
		g.drawImage(theImgSmall,width*2/7,height*17/22,null);
        g.dispose();
        try { 
    		FileOutputStream out=new FileOutputStream(outPath); //先用一个特定的输出文件名 
    		JPEGImageEncoder encoder =JPEGCodec.createJPEGEncoder(out); 
    		JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage); 
    		param.setQuality(100, true);  //
    		encoder.encode(bimage, param); 
    		out.close(); 
    		} catch(Exception e) { 
    			return false; 
			} 
    	return true; 
	}*/
}
